<script setup>
import { reactive,ref } from "vue";
import { User,Lock } from "@element-plus/icons-vue";
import request from "../utils/request";
import { ElMessage } from "element-plus";
import {useUserStore} from "../stores/user.js"
import router from "../router/index.js"


// 双向绑定的数据，可获取输入框的数据，
const loginData = reactive({});

// 自定义表单校验规则，判断确认密码和密码是否一致，下面这个函数里面的三个参数缺一不可
const repeatPwd = (rule,value,callback) =>{
    if(loginData.password !== value){
        callback(new Error("两次输入密码不一致！"))
    }else{
        callback()
    }
}

// 账号和密码的输入规则，配合prop属性使用才有效
const rules = reactive({
  username: [
    { required: true, message: "请输入账号", trigger: "blur" }
  ],
  password:[
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 8, message: "长度为6-8", trigger: "blur" },
  ],
  repassword:[
    { required: true, message: "请确认密码", trigger: "blur" },
    // validator:自定义表单校验规则
    { validator: repeatPwd, trigger: "blur" },
  ]
});

// 表单校验，登陆时传递给后台前的校验，看看是否输入账号和密码
const ruleFormRef = ref()
function regist(){
    ruleFormRef.value.validate(valid=>{
        if(valid){
        //    校验成功
          request.post('/register',loginData).then(res=>{
            if(res.code === "200"){
              ElMessage.success(res.msg)
            }else{
              ElMessage.error(res.msg)
            }
          })
        }else{
            // 校验失败
            
        }
    })
}

const register = () =>{
  router.push("/login")
}
</script>

<template>
  <div>
    <div class="register">
      <el-form
        ref="ruleFormRef"
        :model="loginData"
        status-icon
        :rules="rules"
        size="large"
      >
        <div
          style="
            text-align: center;
            color: dodgerblue;
            font-size: 25px;
            font-weight: bold;
            margin-bottom: 25px;
          "
        >
          注册
        </div>
        <el-form-item prop="username">
          <el-input
            v-model="loginData.username"
            placeholder="请输入账号"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginData.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
          />
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            v-model="loginData.repassword"
            type="password"
            placeholder="请确认密码"
            :prefix-icon="Lock"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="regist">注册</el-button>
        </el-form-item>
        <el-link @click="register">已有帐号？请登录</el-link>
      </el-form>
    </div>
  </div>
</template>

<style>
.register {
  position: absolute;
  width: 400px;
  height: 350px;
  background-color: beige;
  right: 150px;
  top: 220px;
  padding: 10px;
}
</style>